﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using DotNetCore.CAP;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.FrameOrder.Dto;
using NP.BPMReportPlatform.RecurringJobs.Dto;
using NP.Enterprise.Utils.Http;
using SqlSugar;

namespace NP.BPMReportPlatform.RecurringJobs
{

    public class FrameOrderRecurringJob : BpmReportPlatformRecurringJob, IFrameOrderRecurringJob
    {
        private readonly SqlSugarClient _db, _dbPlatform;

        private readonly INPRestHttpHelper _httpClient;

        private readonly string _tokenUrl;
        private readonly string _esbNewErpApi;
        private readonly string _esbNewErpApiSap;

        private ICapPublisher _capBus;
        private readonly string _urlTemplate;

        public FrameOrderRecurringJob(ISqlSugarAppService sqlSugarAppService, ICapPublisher publisher, INPRestHttpHelper httpClient,
        IConfiguration configuration)
        {
            // 通用链接，所以直接用立才中心的url模版
            _urlTemplate = configuration["Nippon:LCZXRZXQGL:template"];
            _capBus = publisher;
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _httpClient = httpClient;
            _tokenUrl = configuration["Nippon:FrameOrder:TokenUrl"];
            _esbNewErpApi = configuration["Nippon:FrameOrder:ESBNEWERPAPI"];
            _esbNewErpApiSap = configuration["Nippon:FrameOrder:ESBNEWERPAPI_SAP"];
        }

        /// <summary>
        /// 每次都是全量更新所有离职人员
        /// </summary>
        /// <returns></returns>
        public async Task UpdateResignationUser()
        {
            // 一个月前的时间 
            var time = DateTime.Now.AddMonths(-1);

            // 获取离职人员
            var userList = await _dbPlatform.Queryable<Users>()
                .Where(b => b.ResignationDate != null && b.ResignationDate >= time).ToListAsync();

            // 获取所有离职人员工号
            var employeeIds = userList.Select(x => x.WorkNumber).Distinct().ToList();

            // 离职员工简单对象，只包含工号和离职日期
            var leaveUsers = new List<ResignationInfo>();

            // 计算人员是否离职后又入职，入职后又离职的情况
            foreach (var id in employeeIds)
            {
                // 判断离职人员是否又入职， 或者入职又离职
                // 首先根据更新时间排序 ，最近更新的排在最前面
                var list = userList.Where(x => x.WorkNumber == id).OrderByDescending(x => x.ModifyDate).ToList();

                if (list.Count() > 1)
                {// 数量大于1，则说明是离职后入职，和入职后离职的情况
                 // 因为排序，所以直接获取最新的一条，判断是否 大于time，大于说明离职，小于或者为null ，一般就是 0001年或者1900年，则说明未离职
                    if (list[0].ResignationDate != null && list[0].ResignationDate >= time)// 离职时间在1个月内的
                    {
                        // 添加离职人员
                        leaveUsers.Add(new ResignationInfo()
                        {
                            WorkNumber = list[0].WorkNumber,
                            ResignationDate = list[0].ResignationDate.Value,// 一定是有值的
                        });
                    }
                }
                else if (list.Count() == 1 && list[0].ResignationDate != null && list[0].ResignationDate >= time)// 正常离职，并且离职时间在1个月内
                {// 数量等于1 并且离职日期大于2022年，说明离职
                    // 添加离职人员
                    leaveUsers.Add(new ResignationInfo()
                    {
                        WorkNumber = list[0].WorkNumber,
                        ResignationDate = list[0].ResignationDate.Value,// 一定是有值的
                    });
                }
            }

            foreach (var kvp in leaveUsers)
            {// 离职日期“小于等于15”包含本月与后面所有的月津贴修改为0

                // 获取离职日
                int.TryParse(kvp.ResignationDate.ToString("dd"), out var day);
                // 获取离职月
                int.TryParse(kvp.ResignationDate.ToString("MM"), out var month);
                // 获取离职年
                int.TryParse(kvp.ResignationDate.ToString("yyyy"), out var year);

                // 获取当前用户当前年的所有补贴推送记录（一般补贴）并更新金额为0
                var entityUaOne = await _db.Queryable<FrameOrderUsualAllowance>()
                    .Where(b => b.employeeId == kvp.WorkNumber && b.allowance_type != "年探亲交通补贴").ToListAsync();
                if (entityUaOne != null && entityUaOne.Count > 0)
                {
                    /*
                     * 计算离职日期是否大于等于15
                     * 如果离职日大于等于15 ，说明包含当月 简易计算方式 
                     * 那日期这里设定为1号， 所以包含当月
                     * 否则设定为27号， 所以不包含当月
                     */
                    var uAList = entityUaOne.Where(
                        x =>
                            new DateTime(Convert.ToInt32(x.year), Convert.ToInt32(x.month), 2) > new DateTime(year, month, day >= 15 ? 27 : 1)).ToList();


                    if (uAList.Count > 0)
                    {// 更新金额为0使用补贴和交通补贴
                        foreach (var list in uAList)
                        {
                            list.allowance_lines = 0;
                            list.allowance_lines2 = 0;
                        }
                        try
                        {
                            _db.BeginTran();
                            await _db.Updateable(uAList).ExecuteCommandAsync();
                            _db.CommitTran();
                        }
                        catch (Exception)
                        {
                            _db.RollbackTran();
                            throw;
                        }
                    }
                }

                // 获取当前用户当前年的所有补贴推送记录（费控补贴）并更新金额为0
                var entityUfOne = await _db.Queryable<FrameOrderUsfeeAllowance>().Where(b => b.employeeId == kvp.WorkNumber && b.allowance_type != "年探亲交通补贴").ToListAsync();
                if (entityUfOne != null && entityUfOne.Count > 0)
                {
                    var ufList = entityUfOne.Where(
                        x =>
                            new DateTime(Convert.ToInt32(x.year), Convert.ToInt32(x.month), 2) > new DateTime(year, month, day >= 15 ? 27 : 1)).ToList();

                    if (ufList.Count > 0)
                    {// 更新金额为0使用补贴和交通补贴
                        foreach (var list in ufList)
                        {
                            list.allowance_lines = 0;
                            list.allowance_lines2 = 0;
                            list.UpdateDate = DateTime.Now; // 修改更新时间，希望能被再次抓取
                        }
                        try
                        {
                            _db.BeginTran();
                            await _db.Updateable(ufList).ExecuteCommandAsync();
                            _db.CommitTran();
                        }
                        catch (Exception)
                        {
                            _db.RollbackTran();
                            throw;
                        }
                    }
                }
            }

            var reimbursementInterface = "交通费用补贴,车辆使用补贴";// 交通费用补贴和车辆使用补贴
            List<ItemData> datalist = new List<ItemData>();

            var usualAllowance = await _db.Queryable<FrameOrderUsualAllowance>().Where(x => employeeIds.Contains(x.employeeId) && reimbursementInterface.Contains(x.allowance_type)).ToListAsync();
            foreach (var resignation in leaveUsers)
            {
                // 只获取交通费用补贴，车辆使用补贴
                List<FrameOrderUsualAllowance> usualAllowance2 = usualAllowance.Where(b => b.employeeId == resignation.WorkNumber).ToList();

                if (usualAllowance2.Count > 0)
                {
                    foreach (FrameOrderUsualAllowance item in usualAllowance2)
                    {
                        ItemData itemInfo = new ItemData
                        {
                            code = "车辆使用费(非框架订单)-个人预算",
                            fiscal_date = item.year + "-" + item.month.PadLeft(2, '0'),
                            budget_amount = "0", // 因为是离职人员，所以固定为0//item.allowance_lines.ToString(),
                            budget_code = "pclsyf2",
                            employee_number = item.employeeId
                        };
                        datalist.Add(itemInfo);
                    }
                }

            }

            if (datalist.Count == 0)
            {
                return;
            }

            string bizId = Guid.NewGuid().ToString();
            string timestamp = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString(); // 同步对应的时间戳

            var temp = new ESBRequestCloudPense
            {
                bizId = bizId,
                timestamp = timestamp,
                data = datalist
            };

            // 提交移动报销
            var headers = new Dictionary<string, string>
            {
                {"requestId", Guid.NewGuid().ToString()},
                {"trackId", Guid.NewGuid().ToString()},
                {"sourceSystem","BPMNEW"},
                {"serviceName", "S_XXX_CloudPense_GetToken_S"}
            };

            // 首先获取token
            string tokenUrl = _tokenUrl;
            var tokenResult = await _httpClient.PostAsync<TokenOutput>(tokenUrl, new TokenInput(), headers);

            var token = tokenResult.resCode == 200000 ? tokenResult.data.access_token : "";
            // 变更serviceName
            headers["serviceName"] = "S_XXX_CloudPense_BudgetSyn_S";
            headers.Add("accessToken", token);

            // 提交数据到移动报销
            var result = await _httpClient.PostAsync<dynamic>(_esbNewErpApi, temp, headers);

            //更新回传给送移动报销数据状态
            if (result != null)
            {
                // 获取真正离职的人员
                var leaveEmployeeIds = leaveUsers.Select(x => x.WorkNumber).ToList();
                // 更新数据的业务状态
                usualAllowance = await _db.Queryable<FrameOrderUsualAllowance>().Where(x => leaveEmployeeIds.Contains(x.employeeId) && reimbursementInterface.Contains(x.allowance_type)
                && x.BusinessType != "1").ToListAsync();
                List<FrameOrderUsfeeAllowance> usfeeAllowances = await _db.Queryable<FrameOrderUsfeeAllowance>().Where(x => leaveEmployeeIds.Contains(x.employeeId) && reimbursementInterface.Contains(x.allowance_type)
                    && x.BusinessType != "1").ToListAsync();

                foreach (var allowance in usualAllowance)
                {
                    allowance.BusinessType = "1";
                    allowance.PushTime = DateTime.Now;
                }

                foreach (var usfeeAllowance in usfeeAllowances)
                {
                    usfeeAllowance.BusinessType = "1";
                    usfeeAllowance.PushTime = DateTime.Now;
                }

                if (usualAllowance.Count > 0)
                {
                    await _db.Updateable(usualAllowance).ExecuteCommandAsync();
                }

                if (usfeeAllowances.Count > 0)
                {
                    await _db.Updateable(usfeeAllowances).ExecuteCommandAsync();
                }
            }
        }

        public async Task SyncFrameOrder()
        {
            // 当年
            string nowYear = DateTime.Now.ToString("yyyy");

            //上年
            // int oldYear = Convert.ToInt32(nowYear) - 1;

            //每页条数
            int pageSize = 200;

            // 当前月份
            int dataMonth = DateTime.Now.Month;

            // var reimbursementInterface = "交通费用补贴,车辆使用补贴";// 交通费用补贴和车辆使用补贴

            #region 推送给云检 批量预算同步（作废，不推给云检了）

            ////  获取去年和今年当前月及之前的普通表数据
            //List<FrameOrderUsualAllowance> usualAllowances = await _db.Queryable<FrameOrderUsualAllowance>().Where(b =>
            //    reimbursementInterface.Contains(b.allowance_type) && ((b.year == nowYear && Convert.ToInt32(b.month) <= dataMonth) /*|| b.year == oldYear.ToString()*/)
            //                                                      && !string.IsNullOrEmpty(b.employeeId)).ToListAsync();

            //// 获取去年和今年当前月及之前的费控表数据
            //List<FrameOrderUsfeeAllowance> usfeeAllowances =
            //    await _db.Queryable<FrameOrderUsfeeAllowance>().Where(b =>
            //        reimbursementInterface.Contains(b.allowance_type) && ((b.year == nowYear && Convert.ToInt32(b.month) <= dataMonth) /*|| b.year == oldYear.ToString()*/)
            //                                                          && !string.IsNullOrEmpty(b.employeeId)).ToListAsync();

            ////数据条数/每页条数=总共页数
            //decimal count2 = Convert.ToDecimal(usualAllowances.Count()) / Convert.ToDecimal(pageSize);

            ////当数据条数/每页条数没有得到整数向上取最大值。例：8/6=1.3333333333333直接取值为2
            //int count = Convert.ToInt32(Math.Ceiling(count2));

            //Dictionary<string, string> headers;
            //List<string> instrumentalist;
            //for (int i = 0; i < count; i++)
            //{
            //    var datalist = new List<ItemData>();
            //    instrumentalist = new List<string>();
            //    List<FrameOrderUsualAllowance> skip = usualAllowances.Skip(i * pageSize).Take(pageSize).ToList();

            //    foreach (FrameOrderUsualAllowance item in skip)
            //    {
            //        ItemData itemInfo = new ItemData
            //        {
            //            code = "车辆使用费(非框架订单)-个人预算",
            //            fiscal_date = item.year + "-" + item.month.PadLeft(2, '0'),
            //            budget_amount = item.allowance_lines.ToString(),
            //            budget_code = "pclsyf2",
            //            employee_number = item.employeeId
            //        };
            //        datalist.Add(itemInfo);
            //        instrumentalist.Add(item.ID.ToString());
            //    }

            //    string bizId = Guid.NewGuid().ToString();
            //    string timestamp = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString(); // 同步对应的时间戳
            //    var ydbxTemp = new ESBRequestCloudPense
            //    {
            //        bizId = bizId,
            //        timestamp = timestamp,
            //        data = datalist
            //    };

            //    headers = new Dictionary<string, string>
            //    {
            //        {"requestId", Guid.NewGuid().ToString()},
            //        {"trackId", Guid.NewGuid().ToString()},
            //        {"sourceSystem","BPMNEW"},
            //        {"serviceName", "S_XXX_CloudPense_GetToken_S"} // 获取token
            //    };

            //    string tokenUrl = _tokenUrl;
            //    var tokenResult = await _httpClient.PostAsync<TokenOutput>(tokenUrl, new TokenInput(), headers);

            //    var token = tokenResult.resCode == 200000 ? tokenResult.data.access_token : "";

            //    headers["serviceName"] = "S_XXX_CloudPense_BudgetSyn_S";
            //    headers.Add("accessToken", token);

            //    // 等待回调
            //    var content = await _httpClient.PostAsync<dynamic>(_esbNewErpApi, ydbxTemp, headers);

            //    //更新回传给送移动报销数据状态
            //    if (content != null)
            //    {
            //        // 设置更新日期
            //        if (instrumentalist.Count > 0)
            //        {
            //            var usualReadyUpdate = new List<FrameOrderUsualAllowance>();
            //            List<FrameOrderUsfeeAllowance> fuseeAllowance = new List<FrameOrderUsfeeAllowance>();
            //            foreach (var item in instrumentalist)
            //            {
            //                var usualAllowance = usualAllowances.FirstOrDefault(x => x.ID == Guid.Parse(item));

            //                if (usualAllowance != null)
            //                {

            //                    usualAllowance.BusinessType = "1";
            //                    usualAllowance.PushTime = DateTime.Now;
            //                    usualReadyUpdate.Add(usualAllowance);
            //                    FrameOrderUsfeeAllowance usfeeList = usfeeAllowances.FirstOrDefault(b => b.employeeId == usualAllowance.employeeId && b.allowance_type == usualAllowance.allowance_type
            //                        && b.year == usualAllowance.year && b.month == usualAllowance.month && b.InstanceNumber == usualAllowance.InstanceNumber);
            //                    if (usfeeList != null)
            //                    {

            //                        usfeeList.BusinessType = "1";
            //                        usfeeList.PushTime = DateTime.Now;
            //                        fuseeAllowance.Add(usfeeList);
            //                    }
            //                }
            //            }

            //            if (usualReadyUpdate.Count > 0)
            //            {
            //                await _db.Updateable(usualReadyUpdate).ExecuteCommandAsync();
            //            }

            //            if (fuseeAllowance.Count > 0)
            //            {
            //                await _db.Updateable(fuseeAllowance).ExecuteCommandAsync();
            //            }
            //        }
            //    }
            //    // 600000毫秒 先暂停 10分钟在推送移动报销， 只暂停当前线程
            //    Thread.Sleep(600000);
            //}
            #endregion

            var sApInterface = "'车辆购置补贴','驻外固定补贴','交通补贴'";

            #region 推送给SAP 薪资科目
            var instrumentalist = new List<string>();

            var usualAllowances = await _db.Queryable<FrameOrderUsualAllowance, FrameOrderMain>((a, b) => new object[]
                 {
                    JoinType.Left, a.InstanceNumber == b.InstanceNumber,
                 }).Where((a, b) =>
                     (sApInterface.Contains(a.allowance_type) ||
                      sApInterface.Contains(a.allowance_type2)) && b.BusinessType == "2")
                 .Select((a, b) => a)
                 .ToListAsync();

            var groupList = usualAllowances.
                GroupBy(x => x.InstanceNumber).Select(x => new { MatchType = x.Key, ItemIDLis = x.ToList() });
            // 生成交通补贴，车辆购置补贴，驻外补贴
            var sapDataList = new List<ItemItem_ZHR_RFC>();
            foreach (var item in groupList)
            {
                var enlistment = item.ItemIDLis.Where(x => x.allowance_type == "车辆购置补贴" && x.allowance_lines > 0).ToList();
                if (enlistment.Count > 0)
                {
                    var entity = enlistment.First();

                    if (entity != null && entity.InstanceNumber != "")
                    {
                        ItemItem_ZHR_RFC itemInfo = new ItemItem_ZHR_RFC
                        {
                            PERNR = entity.employeeId,
                            BEGDA = Convert.ToDateTime(entity.StartDate).ToString("yyyy-MM-dd"),
                            ENDDA = Convert.ToDateTime(entity.EndDate).ToString("yyyy-MM-dd"),
                            SUBTY = "2402",// 车辆购置补贴2402
                            BETRG = entity.allowance_lines.ToString(),
                            TYPE = "",
                            MSG = ""
                        };
                        sapDataList.Add(itemInfo);
                        instrumentalist.Add(entity.InstanceNumber);
                    }
                }

                var enlistment2 = item.ItemIDLis.Where(x => x.allowance_type == "驻外固定补贴" && x.allowance_lines > 0).ToList();
                if (enlistment2.Count > 0)
                {
                    var entity = enlistment2.First();
                    if (entity != null && entity.InstanceNumber != "")
                    {
                        ItemItem_ZHR_RFC itemInfo = new ItemItem_ZHR_RFC
                        {
                            PERNR = entity.employeeId,
                            BEGDA = Convert.ToDateTime(entity.StartDate).ToString("yyyy-MM-dd"),
                            ENDDA = Convert.ToDateTime(entity.EndDate).ToString("yyyy-MM-dd"),
                            SUBTY = "2410",// 驻外固定补贴
                            BETRG = entity.allowance_lines.ToString(),
                            TYPE = "",
                            MSG = ""
                        };
                        sapDataList.Add(itemInfo);
                        instrumentalist.Add(entity.InstanceNumber);
                    }
                }

                var enlistment3 = item.ItemIDLis.Where(x => x.allowance_type2 == "交通补贴" && x.allowance_lines2 > 0).ToList();
                if (enlistment3.Count > 0)
                {
                    var entity = enlistment3.First();
                    if (entity != null && entity.InstanceNumber != "")
                    {
                        ItemItem_ZHR_RFC itemInfo = new ItemItem_ZHR_RFC
                        {
                            PERNR = entity.employeeId,
                            BEGDA = Convert.ToDateTime(entity.StartDate).ToString("yyyy-MM-dd"),
                            ENDDA = Convert.ToDateTime(entity.EndDate).ToString("yyyy-MM-dd"),
                            SUBTY = "2417",// 交通补贴
                            BETRG = entity.allowance_lines2.ToString(),
                            TYPE = "",
                            MSG = ""
                        };
                        sapDataList.Add(itemInfo);
                        instrumentalist.Add(entity.InstanceNumber);
                    }
                }
            }

            var temp = new ESBRequestZHRRFC
            {
                Root = new Root()
                {
                    Name = "urn",
                    Ele = "false",
                    Space = "urn:sap-com:document:sap:rfc:functions",
                },
                ZHR_RFC_WRITE_0014 = new ZHR_RFC_WRITE_0014
                {
                    IT_DATA = new IT_DATA()
                    {
                        item = sapDataList
                    }
                }
            };

            var headers = new Dictionary<string, string>
            {
                {"requestId", Guid.NewGuid().ToString()},
                {"trackId", Guid.NewGuid().ToString()},
                {"sourceSystem", "BPMNEW"},
                {"serviceName", "S_XXX_ERPHR_ZRWrite_S"},
            };

            var str = await _httpClient.PostAsync(_esbNewErpApiSap, JsonConvert.SerializeObject(temp), headers);

            // 返回值

            //更新回传给SAP数据状态
            if (str != null)
            {
                var outData = JsonConvert.DeserializeObject<JObject>(str).Value<JObject>("ZHR_RFC_WRITE_0014Response");
                var itemArray = outData.Value<JObject>("IT_DATA").Value<JArray>("item");
                var reslist = itemArray.ToObject<List<ItemItem_ZHR_RFC>>();
                if (instrumentalist.Count > 0&& reslist.Count>0)
                {
                    var s_instrumentalist = new List<string>();// 同步成功的流程编号
                    var e_instrumentalist = new List<string>();// 同步失败的流程编号
                    for (int i = 0; i < reslist.Count; i++)
                    {
                        if (reslist[i].TYPE == "S")
                        {
                            s_instrumentalist.Add(instrumentalist[i]);
                        }
                        else
                        {
                            e_instrumentalist.Add(instrumentalist[i]);
                        }
                    }
                    if (s_instrumentalist.Count>0)
                    {
                        var frameOrderMainList1 = await _db.Queryable<FrameOrderMain>()
                                              .Where(x => s_instrumentalist.Contains(x.InstanceNumber)).ToListAsync();

                        if (frameOrderMainList1.Count > 0)
                        {
                            foreach (var item in frameOrderMainList1)
                            {
                                item.BusinessType = "1";
                            }
                            await _db.Updateable(frameOrderMainList1).ExecuteCommandAsync();
                        }
                    }
                    if (e_instrumentalist.Count > 0)
                    {
                        var frameOrderMainList2 = await _db.Queryable<FrameOrderMain>()
                                              .Where(x => e_instrumentalist.Contains(x.InstanceNumber)).ToListAsync();

                        if (frameOrderMainList2.Count > 0)
                        {
                            foreach (var item in frameOrderMainList2)
                            {
                                item.BusinessType = "2"; // 同步不成功的改为资金组确认
                            }
                            await _db.Updateable(frameOrderMainList2).ExecuteCommandAsync();
                        }
                    }
                }
            }

            #endregion
        }

        /// <summary>
        /// 手动推送
        /// </summary>
        /// <param name="instanceNumber">单号</param>
        /// <param name="type">推送类型：1-移动报销，2-SAP</param>
        /// <returns></returns>

        public async Task SyncFrameOrder(string instanceNumber,string type)
        {
            // 当年
            string nowYear = DateTime.Now.ToString("yyyy");

            //上年
            // int oldYear = Convert.ToInt32(nowYear) - 1;

            //每页条数
            int pageSize = 1000;

            // 当前月份
            int dataMonth = DateTime.Now.Month;
            //if (type == "1") 
            //{
            //    var reimbursementInterface = "交通费用补贴,车辆使用补贴";// 交通费用补贴和车辆使用补贴

            //    #region 推送给云检 批量预算同步

            //    //  获取去年和今年当前月及之前的普通表数据
            //    List<FrameOrderUsualAllowance> usualAllowances = await _db.Queryable<FrameOrderUsualAllowance>().Where(b =>
            //        reimbursementInterface.Contains(b.allowance_type) && ((b.year == nowYear && Convert.ToInt32(b.month) <= dataMonth) /*|| b.year == oldYear.ToString()*/)
            //                                                          && !string.IsNullOrEmpty(b.employeeId))
            //        .WhereIF(!string.IsNullOrWhiteSpace(instanceNumber),b=>b.InstanceNumber==instanceNumber).ToListAsync();

            //    // 获取去年和今年当前月及之前的费控表数据
            //    List<FrameOrderUsfeeAllowance> usfeeAllowances =
            //        await _db.Queryable<FrameOrderUsfeeAllowance>().Where(b =>
            //            reimbursementInterface.Contains(b.allowance_type) && ((b.year == nowYear && Convert.ToInt32(b.month) <= dataMonth) /*|| b.year == oldYear.ToString()*/)
            //                                                              && !string.IsNullOrEmpty(b.employeeId))
            //        .WhereIF(!string.IsNullOrWhiteSpace(instanceNumber), b => b.InstanceNumber == instanceNumber).ToListAsync();

            //    //数据条数/每页条数=总共页数
            //    decimal count2 = Convert.ToDecimal(usualAllowances.Count()) / Convert.ToDecimal(pageSize);

            //    //当数据条数/每页条数没有得到整数向上取最大值。例：8/6=1.3333333333333直接取值为2
            //    int count = Convert.ToInt32(Math.Ceiling(count2));

            //    Dictionary<string, string> headers;
            //    List<string> instrumentalist;
            //    for (int i = 0; i < count; i++)
            //    {
            //        var datalist = new List<ItemData>();
            //        instrumentalist = new List<string>();
            //        List<FrameOrderUsualAllowance> skip = usualAllowances.Skip(i * pageSize).Take(pageSize).ToList();

            //        foreach (FrameOrderUsualAllowance item in skip)
            //        {
            //            ItemData itemInfo = new ItemData
            //            {
            //                code = "车辆使用费(非框架订单)-个人预算",
            //                fiscal_date = item.year + "-" + item.month.PadLeft(2, '0'),
            //                budget_amount = item.allowance_lines.ToString(),
            //                budget_code = "pclsyf2",
            //                employee_number = item.employeeId
            //            };
            //            datalist.Add(itemInfo);
            //            instrumentalist.Add(item.ID.ToString());
            //        }

            //        string bizId = Guid.NewGuid().ToString();
            //        string timestamp = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString(); // 同步对应的时间戳
            //        var ydbxTemp = new ESBRequestCloudPense
            //        {
            //            bizId = bizId,
            //            timestamp = timestamp,
            //            data = datalist
            //        };

            //        headers = new Dictionary<string, string>
            //    {
            //        {"requestId", Guid.NewGuid().ToString()},
            //        {"trackId", Guid.NewGuid().ToString()},
            //        {"sourceSystem","BPM"},
            //        {"serviceName", "S_XXX_CloudPense_GetToken_S"} // 获取token
            //    };

            //        string tokenUrl = _tokenUrl;
            //        var tokenResult = await _httpClient.PostAsync<TokenOutput>(tokenUrl, new TokenInput(), headers);

            //        var token = tokenResult.resCode == 200000 ? tokenResult.data.access_token : "";

            //        headers["serviceName"] = "S_XXX_CloudPense_BudgetSyn_S";
            //        headers.Add("accessToken", token);


            //        // 等待回调
            //        var content = await _httpClient.PostAsync<dynamic>(_esbNewErpApi, ydbxTemp, headers);

            //        //更新回传给送移动报销数据状态
            //        if (content != null)
            //        {
            //            // 设置更新日期
            //            if (instrumentalist.Count > 0)
            //            {
            //                var usualReadyUpdate = new List<FrameOrderUsualAllowance>();
            //                List<FrameOrderUsfeeAllowance> fuseeAllowance = new List<FrameOrderUsfeeAllowance>();
            //                foreach (var item in instrumentalist)
            //                {
            //                    var usualAllowance = usualAllowances.FirstOrDefault(x => x.ID == Guid.Parse(item));

            //                    if (usualAllowance != null)
            //                    {

            //                        usualAllowance.BusinessType = "1";
            //                        usualAllowance.PushTime = DateTime.Now;
            //                        usualReadyUpdate.Add(usualAllowance);
            //                        FrameOrderUsfeeAllowance usfeeList = usfeeAllowances.FirstOrDefault(b => b.employeeId == usualAllowance.employeeId && b.allowance_type == usualAllowance.allowance_type
            //                            && b.year == usualAllowance.year && b.month == usualAllowance.month && b.InstanceNumber == usualAllowance.InstanceNumber);
            //                        if (usfeeList != null)
            //                        {

            //                            usfeeList.BusinessType = "1";
            //                            usfeeList.PushTime = DateTime.Now;
            //                            fuseeAllowance.Add(usfeeList);
            //                        }
            //                    }
            //                }

            //                if (usualReadyUpdate.Count > 0)
            //                {
            //                    await _db.Updateable(usualReadyUpdate).ExecuteCommandAsync();
            //                }

            //                if (fuseeAllowance.Count > 0)
            //                {
            //                    await _db.Updateable(fuseeAllowance).ExecuteCommandAsync();
            //                }
            //            }
            //        }
            //        // 600000毫秒 先暂停 10分钟在推送移动报销， 只暂停当前线程
            //        Thread.Sleep(600000);
            //    }
            //    #endregion
            //}
            if (type == "2")
            {
                var sApInterface = "'车辆购置补贴','驻外固定补贴','交通补贴'";

                #region 推送给SAP 薪资科目
                List<string> instrumentalist = new List<string>();

                List<FrameOrderUsualAllowance> usualAllowances = await _db.Queryable<FrameOrderUsualAllowance, FrameOrderMain>((a, b) => new object[]
                    {
                    JoinType.Left, a.InstanceNumber == b.InstanceNumber,
                    }).Where((a, b) =>
                        (sApInterface.Contains(a.allowance_type) ||
                         sApInterface.Contains(a.allowance_type2)) && b.BusinessType == "2")
                    .Select((a, b) => a)
                    .WhereIF(!string.IsNullOrWhiteSpace(instanceNumber), a=> a.InstanceNumber == instanceNumber)
                    .ToListAsync();

                var groupList = usualAllowances.
                    GroupBy(x => x.InstanceNumber).Select(x => new { MatchType = x.Key, ItemIDLis = x.ToList() });
                // 生成交通补贴，车辆购置补贴，驻外补贴
                var sapDataList = new List<ItemItem_ZHR_RFC>();
                foreach (var item in groupList)
                {
                    var enlistment = item.ItemIDLis.Where(x => x.allowance_type == "车辆购置补贴" && x.allowance_lines > 0).ToList();
                    if (enlistment.Count > 0)
                    {
                        var entity = enlistment.First();

                        if (entity != null && entity.InstanceNumber != "")
                        {
                            ItemItem_ZHR_RFC itemInfo = new ItemItem_ZHR_RFC
                            {
                                PERNR = entity.employeeId,
                                BEGDA = Convert.ToDateTime(entity.StartDate).ToString("yyyy-MM-dd"),
                                ENDDA = Convert.ToDateTime(entity.EndDate).ToString("yyyy-MM-dd"),
                                SUBTY = "2402",// 车辆购置补贴2402
                                BETRG = entity.allowance_lines.ToString(),
                                TYPE = "",
                                MSG = ""
                            };
                            sapDataList.Add(itemInfo);
                            instrumentalist.Add(entity.InstanceNumber);
                        }
                    }

                    var enlistment2 = item.ItemIDLis.Where(x => x.allowance_type == "驻外固定补贴" && x.allowance_lines > 0).ToList();
                    if (enlistment2.Count > 0)
                    {
                        var entity = enlistment2.First();
                        if (entity != null && entity.InstanceNumber != "")
                        {
                            ItemItem_ZHR_RFC itemInfo = new ItemItem_ZHR_RFC
                            {
                                PERNR = entity.employeeId,
                                BEGDA = Convert.ToDateTime(entity.StartDate).ToString("yyyy-MM-dd"),
                                ENDDA = Convert.ToDateTime(entity.EndDate).ToString("yyyy-MM-dd"),
                                SUBTY = "2410",// 驻外固定补贴
                                BETRG = entity.allowance_lines.ToString(),
                                TYPE = "",
                                MSG = ""
                            };
                            sapDataList.Add(itemInfo);
                            instrumentalist.Add(entity.InstanceNumber);
                        }
                    }

                    var enlistment3 = item.ItemIDLis.Where(x => x.allowance_type2 == "交通补贴" && x.allowance_lines2 > 0).ToList();
                    if (enlistment3.Count > 0)
                    {
                        var entity = enlistment3.First();
                        if (entity != null && entity.InstanceNumber != "")
                        {
                            ItemItem_ZHR_RFC itemInfo = new ItemItem_ZHR_RFC
                            {
                                PERNR = entity.employeeId,
                                BEGDA = Convert.ToDateTime(entity.StartDate).ToString("yyyy-MM-dd"),
                                ENDDA = Convert.ToDateTime(entity.EndDate).ToString("yyyy-MM-dd"),
                                SUBTY = "2417",// 交通补贴
                                BETRG = entity.allowance_lines2.ToString(),
                                TYPE = "",
                                MSG = ""
                            };
                            sapDataList.Add(itemInfo);
                            instrumentalist.Add(entity.InstanceNumber);
                        }
                    }
                }

                var temp = new ESBRequestZHRRFC
                {
                    Root = new Root()
                    {
                        Name = "urn",
                        Ele = "false",
                        Space = "urn:sap-com:document:sap:rfc:functions",
                    },
                    ZHR_RFC_WRITE_0014 = new ZHR_RFC_WRITE_0014
                    {
                        IT_DATA = new IT_DATA()
                        {
                            item = sapDataList
                        }
                    }
                };

              var  headers = new Dictionary<string, string>
                {
                    {"requestId", Guid.NewGuid().ToString()},
                    {"trackId", Guid.NewGuid().ToString()},
                    {"sourceSystem", "BPM"},
                    {"serviceName", "S_XXX_ERPHR_ZRWrite_S"},
                };

                var str = await _httpClient.PostAsync(_esbNewErpApiSap, JsonConvert.SerializeObject(temp), headers);

                // 返回值

                //更新回传给SAP数据状态
                if (str != null)
                {
                    var outData = JsonConvert.DeserializeObject<JObject>(str).Value<JObject>("ZHR_RFC_WRITE_0014Response");
                    var itemArray = outData.Value<JObject>("IT_DATA").Value<JArray>("item");
                    var reslist = itemArray.ToObject<List<ItemItem_ZHR_RFC>>();
                    if (instrumentalist.Count > 0 && reslist.Count > 0)
                    {
                        var s_instrumentalist = new List<string>();// 同步成功的流程编号
                        var e_instrumentalist = new List<string>();// 同步失败的流程编号
                        for (int i = 0; i < reslist.Count; i++)
                        {
                            if (reslist[i].TYPE == "S")
                            {
                                s_instrumentalist.Add(instrumentalist[i]);
                            }
                            else
                            {
                                e_instrumentalist.Add(instrumentalist[i]);
                            }
                        }
                        if (s_instrumentalist.Count > 0)
                        {
                            var frameOrderMainList1 = await _db.Queryable<FrameOrderMain>()
                                                  .Where(x => s_instrumentalist.Contains(x.InstanceNumber)).ToListAsync();

                            if (frameOrderMainList1.Count > 0)
                            {
                                foreach (var item in frameOrderMainList1)
                                {
                                    item.BusinessType = "1";
                                }
                                await _db.Updateable(frameOrderMainList1).ExecuteCommandAsync();
                            }
                        }
                        if (e_instrumentalist.Count > 0)
                        {
                            var frameOrderMainList2 = await _db.Queryable<FrameOrderMain>()
                                                  .Where(x => e_instrumentalist.Contains(x.InstanceNumber)).ToListAsync();

                            if (frameOrderMainList2.Count > 0)
                            {
                                foreach (var item in frameOrderMainList2)
                                {
                                    item.BusinessType = "2"; // 同步不成功的改为资金组确认
                                }
                                await _db.Updateable(frameOrderMainList2).ExecuteCommandAsync();
                            }
                        }
                    }
                }

                #endregion
            }
        }
        public async Task SendEmail()
        {
            return;
            // 当前日期
            DateTime nowTime = DateTime.Now;
            //交通费用，车辆购置，
            List<InfoResultDto> detailData = await _db.Queryable<FrameOrderMain, BusinessProcessesNew>((a, b) => new object[]
                {
                    JoinType.Left, a.InstanceNumber == b.InstanceId,
                }).Where((a, b) => b.ProcessStatusCode == "approved")
                .Where((a, b) => a.SubsidyEndDate != null && Convert.ToDateTime(a.SubsidyEndDate.Value.AddMonths(-1).ToString("yyyy-MM-dd")) >= Convert.ToDateTime(nowTime.ToString("yyyy-MM-dd")))
                .Select((a, b) =>
                    new InfoResultDto
                    {
                        InstanceId = a.InstanceNumber,
                        ApplyNumber = a.ApplyNumber,
                        ProcessStartTime = b.StartTime,
                        ProcessId = b.ProcessId.Value,
                        ProcessName = b.ProcessTopic,
                    }).ToListAsync();
            //人事驻外
            List<InfoResultDto> detailData2 = await _db.Queryable<FrameOrderMain, FrameOrderChildrszwbt, BusinessProcessesNew>((a, b, c) => new object[]
                {
                    JoinType.Left, a.ID == b.MainID,
                    JoinType.Left, a.InstanceNumber == c.InstanceId,
                }).Where((a, b, c) => c.ProcessStatusCode == "approved")
                .Where((a, b, c) => b.AssignDateend != null && Convert.ToDateTime(b.AssignDateend.Value.AddMonths(-1).ToString("yyyy-MM-dd")) >= Convert.ToDateTime(nowTime.ToString("yyyy-MM-dd")))
                .Select((a, b, c) =>
                    new InfoResultDto
                    {
                        InstanceId = a.InstanceNumber,
                        ApplyNumber = a.ApplyNumber,
                        ProcessStartTime = c.StartTime,
                        ProcessId = c.ProcessId.Value,
                        ProcessName = c.ProcessTopic,
                    }).ToListAsync();
            //高管
            List<InfoResultDto> detailData3 = await _db.Queryable<FrameOrderSenior, FrameOrderSeniorDetails, BusinessProcessesNew>((a, b, c) => new object[]
                {
                     JoinType.Left, a.SeniorID == b.SeniorID,
                    JoinType.Left, a.InstanceNumber == c.InstanceId,
                }).Where((a, b, c) => c.ProcessStatusCode == "approved")
                .Where((a, b, c) => b.EndTime != null && Convert.ToDateTime(b.EndTime.Value.AddMonths(-1).ToString("yyyy-MM-dd")) >= Convert.ToDateTime(nowTime.ToString("yyyy-MM-dd")))
                .Select((a, b, c) =>
                    new InfoResultDto
                    {
                        InstanceId = a.InstanceNumber,
                        ApplyNumber = b.ApplyNumber,
                        ProcessStartTime = c.StartTime,
                        ProcessId = c.ProcessId.Value,
                        ProcessName = c.ProcessTopic,
                    }).ToListAsync();


            var detailDataAll = detailData.Union(detailData2).Union(detailData3).ToList();

            var allWorkNumber = detailDataAll.Select(z => z.ApplyNumber);

            var totalUsers = await _dbPlatform.Queryable<Users>()
                .Where(x => allWorkNumber.Contains(x.WorkNumber)).ToListAsync();

            foreach (var item in detailDataAll)
            {
                var userInfo = totalUsers.First(x => x.WorkNumber == item.ApplyNumber);

                var newUrl = _urlTemplate.Replace("{str}", item.InstanceId);

                await _capBus.PublishAsync("bpmnew.EmailAppService.SendEmailAsync",
                    new SendEmailSimpleDto()
                    {
                        To = userInfo.Email,
                        Subject = "框架订单到期提醒",
                        Body = $"您发起的{item.ProcessName}框架订单流程即将到期，流程编号:<a href='{newUrl}'>{item.InstanceId}<a/>",
                        InstanceNumber = item.InstanceId
                    });
            }
        }
    }
}
